package com.hethongviet.job.pages;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import group.pals.android.lib.ui.filechooser.FileChooserActivity;
import group.pals.android.lib.ui.filechooser.io.LocalFile;

import com.hethongviet.job.AppMain;
import com.hethongviet.job.R;
import com.hethongviet.job.helpers.ServiceHelper;
import com.hethongviet.job.helpers.download.ImageLoadTask;
import com.hethongviet.job.helpers.download.TouchImageView;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class ViewImageActivity extends Activity
{
	private ImageView _imageView = null;
	// private TextView _textViewImageName = null;
	private ProgressBar _progressBar = null;
	private int _requestType = AppMain.REQUEST_VIEW_IMAGE;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		/* Full screen */
		// AppMain.prepareWindow(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.page_view_image);

		_imageView = (TouchImageView) findViewById(R.id.imageView);
		// _imageView.setImageBitmap(AppMain._imageFileTemp.getBitmap());

		_progressBar = (ProgressBar) findViewById(R.id.progressBar);

		_requestType = getIntent().getExtras().getInt("request_type");

		if (_requestType == AppMain.REQUEST_CAMERA
				|| _requestType == AppMain.REQUEST_CHOOSE_FILE_IMAGE)
		{
			AppMain.debug("-----camera");
			_imageView.setImageBitmap(AppMain._imageFileView.getBitmap());
			_imageView.setVisibility(View.VISIBLE);
			_progressBar.setVisibility(View.GONE);
		}
		else if (_requestType == AppMain.REQUEST_DOWNLOAD_IMAGE
				&& AppMain._imageFileView.getBitmap() == null)
		{
			AppMain.debug("-----download image!!!");
			String imageName = AppMain._imageFileView.getName();
			AppMain.debug("-----download image1!!! imageName=" + imageName);
			if (imageName != null)
			{
				AppMain.debug("-----download image2!!!");

				String preUrl = ServiceHelper.URL + "/"
						+ AppMain._user.getDomain();

				if (AppMain._user.getDomain() == null
						|| AppMain._user.getDomain().trim().equals("")) preUrl = ServiceHelper.URL;
				AppMain.debug("-----download image url: "+preUrl
						+ ServiceHelper.URL_DOWNLOAD_IMAGE + imageName);
				new ImageLoadTask(this, _imageView, AppMain._imageFileView, _progressBar).execute(preUrl
						+ ServiceHelper.URL_DOWNLOAD_IMAGE + imageName);
			}
		}
		else
		{
			AppMain.debug("-----view image!!!!!");
			_imageView.setImageBitmap(AppMain._imageFileView.getBitmap());
			_imageView.setVisibility(View.VISIBLE);
			_progressBar.setVisibility(View.GONE);
		}

		setResult(RESULT_CANCELED);
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
			case AppMain.REQUEST_CHOOSE_DIRECTORY:
				if (resultCode == RESULT_OK)
				{
					List<LocalFile> localFiles = (List<LocalFile>) data.getSerializableExtra(FileChooserActivity.Results);
					File directory = localFiles.get(0);
					/* Save image */
					try
					{
						String imageName = AppMain._imageFileView.getOriginalName();

						FileOutputStream fileOutputStream = new FileOutputStream(directory.getAbsolutePath()
								+ "/" + imageName);

						String fileType = AppMain.getFileType(imageName);
						AppMain._imageFileView.getBitmap().compress(AppMain.getBitmapCompressFotmat(fileType), 100, fileOutputStream);

						fileOutputStream.flush();
						fileOutputStream.close();

						AppMain.showAlert(this, getString(R.string.textMessageDownloadFileSuccess)
								+ ": "
								+ directory.getAbsolutePath()
								+ "/" + imageName, false);

					} catch (FileNotFoundException e)
					{
						e.printStackTrace();
					} catch (IOException e)
					{
						e.printStackTrace();
					}
				}
				break;
			case AppMain.REQUEST_CHOOSE_FILE_IMAGE:
				if (resultCode == RESULT_OK)
				{
					List<LocalFile> localFiles = (List<LocalFile>) data.getSerializableExtra(FileChooserActivity.Results);
					File file = localFiles.get(0);
					String fileName = file.getName();
					String fileType = AppMain.getFileType(fileName);

					if (fileType == null || !AppMain.isImageSupported(fileType))
					{
						AppMain.showAlert(this, R.string.textErrorFileNotSupport, false);
						return;
					}
					Bitmap bitmap = null;

					// try
					// {
					// InputStream inputStream = new BufferedInputStream(
					// new FileInputStream(file));

					bitmap = AppMain.decodeFile(file);

					// if (inputStream != null) inputStream.close();
					// } catch (FileNotFoundException e)
					// {
					// e.printStackTrace();
					// } catch (IOException e)
					// {
					// e.printStackTrace();
					// }
					AppMain._imageFileView.setBitmap(bitmap);
					AppMain._imageFileView.setOriginalName(fileName);
					_imageView.setImageBitmap(bitmap);
					// _textViewImageName.setText(fileName);
				}

				break;
			case AppMain.REQUEST_CAMERA:
				if (resultCode == RESULT_OK)// ->View image
				{
					AppMain._imageFileView = AppMain.closeCamera(this, data);

					_imageView.setImageBitmap(AppMain._imageFileView.getBitmap());
					// _textViewImageName.setText(AppMain._imageFileView.getName());
				}
				break;
			default:
				break;
		}
	}

	@Override
	public void onBackPressed()
	{
		Intent intent = new Intent();
		setResult(RESULT_CANCELED, intent);
		super.onBackPressed();
	}

	@Override
	protected void onDestroy()
	{
		AppMain.hideAllDialog();
		System.gc();
		super.onDestroy();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.clear();
		if (_progressBar.isShown()) return false;
		MenuInflater menuInflater = getMenuInflater();
		switch (_requestType)
		{
			case AppMain.REQUEST_CAMERA:
				menuInflater.inflate(R.menu.menu_option_view_image_camera, menu);
				break;
			case AppMain.REQUEST_CHOOSE_FILE_IMAGE:
				menuInflater.inflate(R.menu.menu_option_view_image_choose_file, menu);
				break;
			case AppMain.REQUEST_DOWNLOAD_IMAGE:
				menuInflater.inflate(R.menu.menu_option_view_image_download, menu);
				break;
			case AppMain.REQUEST_VIEW_IMAGE:
				menuInflater.inflate(R.menu.menu_option_view_image, menu);
				break;

			default:
				break;
		}

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.menuItemAcount)
		{
			AppMain.showDialogList(this, AppMain.DIALOG_ACCOUNT);
		}
		else if (item.getItemId() == R.id.menuItemSkype)
		{
			AppMain.startSkype(this);
		}
		else if (item.getItemId() == R.id.menuItemDownload)
		{
			AppMain.showFileChooser(this, AppMain.REQUEST_CHOOSE_DIRECTORY);
		}
		else if (item.getItemId() == R.id.menuItemRebrowsing)
		{
			AppMain.showFileChooser(ViewImageActivity.this, AppMain.REQUEST_CHOOSE_FILE_IMAGE);
		}
		else if (item.getItemId() == R.id.menuItemUseImage)
		{
			Intent intent = new Intent();
			setResult(RESULT_OK, intent);
			finish();
		}
		else if (item.getItemId() == R.id.menuItemReshot)
		{
			// Intent intent = new Intent(ViewImageActivity.this,
			// CameraActivity.class);
			// startActivityForResult(intent, AppMain.REQUEST_CAMERA);

			AppMain.openCamera(this);
		}
		return true;
	}

	public int getScreenWidth()
	{
		android.view.Display display = getWindowManager().getDefaultDisplay();
		return display.getWidth();
	}

	public int getScreenHeight()
	{
		android.view.Display display = getWindowManager().getDefaultDisplay();
		return display.getHeight();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		switch (ImageLoadTask._errorCode)
		{
			case ImageLoadTask.ERROR_CONNECTION:
				AppMain.showAlert(this, R.string.textErrorNetwork, true);
				break;
			case ImageLoadTask.ERROR_LOAD_DECODE_IMAGE:
				AppMain.showAlert(this, R.string.textErrorDecodeImage, true);
				break;
			case ImageLoadTask.ERROR_URL_NOT_EXIST:
				AppMain.showAlert(this, R.string.textErrorURLNotExist, true);
				break;
			case ImageLoadTask.STATUS_SUCCESS:
				break;
			default:
				break;
		}
		ImageLoadTask._errorCode = ImageLoadTask.STATUS_NONE;

		super.onWindowFocusChanged(hasFocus);
	}
}
